package com.sparkseries.common.security.filter;

import com.sparkseries.common.security.domain.SecurityUser;
import com.sparkseries.common.security.exception.CustomException;
import com.sparkseries.common.security.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * JWT检测过滤器
 */
@Component
public class JwtCheckFilter extends OncePerRequestFilter {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 放行登录接口
        if (request.getRequestURI().equals("/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 从请求头中获取Token
        String jwt = request.getHeader("Authorization");

        // 从Redis获取对应Token
        String redisToken = stringRedisTemplate.opsForValue().get("loginToken:" + jwt);

        // Token不存在 表示已经退出登录了
        if (Objects.isNull(redisToken)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 校验Token
        if (!jwtUtil.verifyToken(jwt)) {
            throw new CustomException();
        }

        // 获取用户信息
        SecurityUser user = jwtUtil.getUserInfo(jwt);

        // 用户名密码认证Token
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

        // 将Token放入的安全请求上下文中
        SecurityContextHolder.getContext().setAuthentication(token);

        filterChain.doFilter(request, response);
    }
}
